% multi-channel transmitter and Lms equalizer simulation
% for matlab simulation
close all;

%% ------------------------------params-----------------------------
pilotLen = 1e6;
M = 4;
tapLen = 12;
ref = 6;
SNR = 28;
systemDelay = dsp.Delay(1);
%% -----------------------------tx------------------------------
x = exp(sqrt(-1) * (2 * pi * randi([0, M - 1], pilotLen, 1) / M)) * 2^11;

%% ------------------------------channel------------------------------


h = [1,0.5*exp(1i*pi/6),0.1*exp(-1i*pi/8)];
rx = awgn(systemDelay(filter(h,1,x)),SNR,'measured');
rx = rx / max(abs(rx))* 2^11;
rx = floor(rx*0.8);

rx = gardner_res/2^11;
x = tx_msg;
eq = comm.LinearEqualizer('NumTaps',tapLen,'ReferenceTap',ref,'Constellation',pskmod(0:3,4,pi/4));
rxDelay = finddelay(rx,x);
eqInfo = info(eq);
totalDelay = rxDelay + eqInfo.Latency;
release(eq);
% eq.InputDelay = rxDelay;
[y2,err2,weights2] = eq(rx,x(rxDelay:end));
constell3 = comm.ConstellationDiagram('NumInputPorts',2);
constell3(rx,y2);
figure
plot(abs(err2))
xlabel('Symbols')
ylabel('Error Magnitude')
legend('rxDelayed','rxDelayRemoved')
grid on

figure;
subplot(211);bar(real(y2(100000:100100)));
subplot(212);bar(imag(y2(100000:100100)));
%% ------------------------------rx------------------------------
%------------------------------lms------------------------------

mu = 0.01;% step size
weight = zeros(tapLen,1);
weight(floor(tapLen/2)) = 1;
index = 1;
in = zeros(tapLen,1);
y = zeros(pilotLen-tapLen+1,1);
for i = tapLen:length(rx)
   in = rx(i:-1:i-tapLen+1);%load data into sliding window
   y(index) = weight' * in;% calculate weighted output
   e = x(i-ref) - y(index);% calculate error
%    e = 0 - y(index);% calculate error
   weight = weight + mu * conj(e)/2^11 * in/2^11;% update weight
   index = index + 1;
end
figure;plot(rx,'r*');hold on;plot(y,'bs');hold off;
figure;
subplot(211);bar(real(y(100000:100100)));
subplot(212);bar(imag(y(100000:100100)));